package com.kaka.starter.token.config;

import com.kaka.starter.token.dto.TokenParamDTO;
import com.kaka.starter.token.properties.TokenProperties;
import com.kaka.starter.token.service.TokenCheckService;
import com.kaka.starter.token.annotations.aop.ConsoleTokenAspect;
import com.kaka.starter.token.service.TokenService;
import com.kaka.starter.token.util.HeaderUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.util.StringUtils;

/**
 * @author kaka
 * @Date 2019-09-04
 */

@Configuration
@EnableConfigurationProperties({TokenProperties.class})
public class TokenConfig {

    private static final Logger logger = LoggerFactory.getLogger(TokenConfig.class);

    @Bean
    @ConditionalOnMissingBean(ConsoleTokenAspect.class)
    public ConsoleTokenAspect consoleTokenAspect() {
        return new ConsoleTokenAspect();
    }

    @Bean
    @ConditionalOnMissingBean(TokenService.class)
    public TokenService tokenService() {
        return new TokenService();
    }

    @Bean
    @ConditionalOnMissingBean(TokenCheckService.class)
    public TokenCheckService tokenCheckService() {
        return new TokenCheckService();
    }

    @Autowired
    private TokenProperties tokenProperties;

    @Bean
    public TokenParamDTO tokenParamDTO() throws Exception {
        if (StringUtils.isEmpty(tokenProperties.getAuth())
                || StringUtils.isEmpty(tokenProperties.getAuthSecret())) {
            logger.error("[config] token配置不能为空");
            throw new Exception("[config] token配置不能为空");
        }
        HeaderUtils.setAuth(tokenProperties.getAuth());
        HeaderUtils.setAuthSecret(tokenProperties.getAuthSecret());
        return new TokenParamDTO()
                .setAuth(tokenProperties.getAuth())
                .setAuthSecret(tokenProperties.getAuthSecret());
    }
}
